/*
Copyright 2010 Dmitry Barashev

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package net.barashev.seclub.corpus.wikipedia;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class WikipediaExportFileParser extends DefaultHandler {
    private Doc doc;
    private Object trigger = new Object();
    private Callback callback;
    private int level = 0;
    private Thread thread;
    private static int threadCount = 0;

    public static interface Callback {
        void run(Doc doc);
    }

    public static class Doc {
        StringBuilder contentBuffer = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<html>");
        int id;
        StringBuilder cdataBuffer;
        String content;
    }

    @Override
    public void startDocument() throws SAXException {
    }

    @Override
    public void endDocument() throws SAXException {
        notifyCallback(false);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if ("id".equals(qName) && level == 3) {
            doc.id = Integer.parseInt(doc.cdataBuffer.toString());
        } else if ("title".equals(qName)) {
            doc.contentBuffer.append("<head><title>").append(doc.cdataBuffer).append("</title></head>\n");
            doc.cdataBuffer = null;
        } else if ("text".equals(qName)) {
            doc.contentBuffer.append("<body><![CDATA[").append(doc.cdataBuffer).append("\n]]></body>\n");
            doc.cdataBuffer = null;
        } else if ("page".equals(qName)) {
            doc.contentBuffer.append("</html>");
            doc.content = doc.contentBuffer.toString();
            notifyCallback(true);
            doc = null;
        }
        level--;
    }

    private void notifyCallback(boolean wait) {
        if (this.trigger == null) {
            return;
        }
        synchronized (this.trigger) {
            if (this.callback != null) {
                this.callback.run(this.doc);
            }
            if (wait) {
                try {
                    this.trigger.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        if ("page".equals(qName)) {
            doc = new Doc();
        } else if ("title".equals(qName) || "text".equals(qName) ||"id".equals(qName)) {
            doc.cdataBuffer = new StringBuilder();
        }
        level++;
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        if (doc != null && doc.cdataBuffer != null) {
            doc.cdataBuffer.append(ch, start, length);
        }
    }

    public void getNextDocument(Callback c) {
        synchronized (this.trigger) {
            this.callback = c;
            this.trigger.notifyAll();
        }
    }

    public void start(final InputStream input, Callback callback) {
        this.callback = callback;
        this.thread = new Thread(new Runnable() {
            public void run() {
                try {
                    SAXParserFactory.newInstance().newSAXParser().parse(input, WikipediaExportFileParser.this);
                } catch (SAXException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        this.thread.start();
    }

    public void stop() {
        if (this.trigger == null) {
            return;
        }
        synchronized (this.trigger) {
            this.trigger.notifyAll();
            this.trigger = null;
        }
    }
}
